/**
 * Created on May 18, 2007
 */
package jvs.vfs.sound;

import java.util.ArrayList;
import java.util.List;

import javax.sound.sampled.spi.AudioFileReader;
import javax.sound.sampled.spi.FormatConversionProvider;

import jvs.vfs.FileSystem;
import jvs.vfs.sound.sampled.spi.BasicAudioFileReader;
import jvs.vfs.sound.sampled.spi.BasicFormatConversionProvider;
import jvs.vfs.util.Log;
import x.java.io.File;

/**
 * @author qiangli
 * 
 */
public class AudioSystem {
	private static AudioSystem instance = new AudioSystem();
	
	private AudioSystem() {
	}

	public static AudioSystem getAudioSystem() {
		return instance;
	}
	
	public void init(File providerDir) {
		File[] files = (File[]) providerDir.listFiles();
		if (files == null || files.length ==0) {
			return;
		}
		List<AudioFileReader> readers = new ArrayList<AudioFileReader>();
		List<FormatConversionProvider> converters = new ArrayList<FormatConversionProvider>();
		ClassLoader cl = FileSystem.getFileSystem().getVfsClassLoader();
		for (int i = 0; i < files.length; i++) {
			Log.log(Log.DEBUG,this,files[i]);
			
			String[] names = files[i].getContent().split("[\r\n]");
			if (names == null || names.length == 0 ) {
				continue;
			}
			for (int j = 0; j < names.length; j++) {
				try {
					String n = names[j];
					if (n == null) {
						continue;
					}
					n = n.trim();
					if (n.length() == 0) {
						continue;
					}
					Log.log(Log.DEBUG,this,n);
					
					Class<?> c = cl.loadClass(n);
					Object o = c.newInstance();
					
					Log.log(Log.INFO,this,o);
					if (o instanceof AudioFileReader) {
						readers.add((AudioFileReader)o);
					} else if (o instanceof FormatConversionProvider) {
						converters.add((FormatConversionProvider)o);
					}
				} catch (ClassNotFoundException e) {
					Log.log(Log.INFO,this,"ClassNotFound: "+e.getMessage());
				} catch (Exception e) {
					Log.log(Log.ERROR,this,e);
				}
			}
		}
		//
		BasicAudioFileReader.init(readers);
		BasicFormatConversionProvider.init(converters);
	}
}
